import 'dart:convert';

/// Object 扩展 on dynamic运行时会转换类型扩展无法识别
extension ObjectExt on Object? {
  /// 对象转json String
  String? jsonToString() {
    if (this == null) return null;
    return jsonEncode(this);
  }

  /// 对象转String
  /// prefix 前缀
  /// suffix 后缀
  /// placeholder 占位符
  /// multiple 倍数
  /// fixed 截取位数
  /// abs 取绝对值
  ///
  // String toNumStr(
  //     {String prefix = "",
  //     String suffix = "",
  //     String placeholder = "--",
  //     int multiple = 1,
  //     int fixed = -1,
  //     bool abs = false}) {
  //   double? num = this.toDouble();
  //   if (num == null) {
  //     return placeholder;
  //   }
  //   if (abs) {
  //     num = num.abs();
  //   }
  //   Decimal decimal =
  //       Decimal.parse(num.toString()) * Decimal.parse(multiple.toString());
  //   String str;
  //   if (fixed != -1) {
  //     str = decimal.toStringAsFixed(fixed);
  //   } else {
  //     str = decimal.toString();
  //   }
  //   return prefix + str + suffix;
  // }

  /// 百分比字符串
  // String toRateStr(
  //     {String placeholder = "0.00",
  //     String suffix = "%",
  //     int fixed = 2,
  //     int multiple = 1}) {
  //   return ((this.toDouble() ?? 0) * multiple)
  //       .toNumStr(placeholder: placeholder, fixed: fixed, suffix: suffix);
  // }

  /// 对象转 double
  double? toDouble() {
    if (this == null) {
      return null;
    } else if (this is double) {
      return this as double;
    } else if (this is int) {
      return (this as int) * 1.0;
    } else if (this is String) {
      try {
        return double.parse(this as String);
      } catch (e) {
        return null;
      }
    } else {
      return null;
    }
  }

  T? parseParams<T>() {
    return parseObject<T>(this);
  }
  ///运单状态(1.待接单 2.待装货 3.待卸货 4.待签收 5.已签收 6.已完成 7.已取消)
  String statusName(){
    switch(this){
      case 1:
        return '待接单';
      case 2:
        return '待装货';
      case 3:
        return '待卸货';
      case 4:
        return '待签收';
      case 5:
        return '已签收';
      case 6:
        return '已完成';
      case 7:
        return '已取消';
      default:
        return '';
    }
  }

}

T? parseObject<T>(Object? data) {
  if (data == null) {
    return null;
  }
  String params = data.toString();
  try {
    if (T == int) {
      return int.parse(params) as T?;
    } else if (T == double) {
      return double.parse(params) as T?;
    } else if (T == num) {
      return num.parse(params) as T?;
    } else if (T == bool) {
      if (params == "true") {
        return true as T?;
      } else if (params == "false") {
        return false as T?;
      } else {
        return null;
      }
    } else if (T == String) {
      return params as T;
    }else{
      return data as T;
    }
  }catch(e){
    return null;
  }
}
